package hsintiao.com.xintiaoAPP.Interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.JWTVerifier;
import hsintiao.com.xintiaoAPP.annotation.PassToken;
import hsintiao.com.xintiaoAPP.annotation.UserLoginToken;
import hsintiao.com.xintiaoAPP.entity.User;
import hsintiao.com.xintiaoAPP.service.UserService;
import hsintiao.com.xintiaoAPP.util.PackageReturnResult;
import hsintiao.com.xintiaoAPP.util.RedisUtils;
import hsintiao.com.xintiaoAPP.util.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 拦截器
 * @author qiaoyn
 * @date 2019/06/14
 */
@CrossOrigin
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {


        httpServletResponse.setHeader("Access-Control-Allow-Origin","*");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");
        httpServletResponse.setHeader("Access-Control-Allow-methods","GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
        httpServletResponse.setHeader("Access-Control-Max-age","86400");
        httpServletResponse.setHeader("Access-Control-Allow-Headers","*");
        if(HttpMethod.OPTIONS.toString().equals(httpServletRequest.getMethod())){
            httpServletResponse.setStatus(HttpStatus.NO_CONTENT.value());
            return false;
        }
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        String uri = httpServletRequest.getRequestURI();
        System.out.println(uri);
        //放行支付宝回调接口
        if(uri.equals("/alipay/returnUrl")){
            return true;
        }
        if(uri.equals("/alipay/notifyUrl")){
            return true;
        }
        if(uri.equals("/error")){
            return true;
        }
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        /*Cookie[] cookies = httpServletRequest.getCookies();
        System.out.println("cookies="+cookies);
        for (Cookie c:
             cookies) {
            System.out.println(c.getName()+"="+c.getValue());
        }*/
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        String cookie = httpServletRequest.getHeader("cookie");// 从 http 请求头中取出 cookie
        if(cookie!= null){
            String[] split = cookie.trim().split(";");
            for (String s:
                    split) {
                String[] split1 = s.trim().split("=");
                if(split1[0].equals("cookie")){
                    cookie=split1[1];
                }
                if(split1[0].equals("jwt-cookie")){
                    cookie=split1[1];
                }
            }
        }
        /*if(cookie != null){
            if(token==null){
                token=cookie;
            }
        }*/
        System.out.println("cookie="+cookie);
        //System.out.println("token="+token);
        /*if(token == null){
            token="zs01";
        }*/
        String getToken = RedisUtils.INSTANCE.get(cookie);
        //cookei不为空且有效，返回cookie
        if(getToken!= null){
            //cookie=getToken;
            System.out.println("getToken="+cookie);
            Cookie cookie1 = new Cookie("jwt-cookie", cookie);
            cookie1.setPath("/");
            cookie1.setMaxAge(60*60*24);
            cookie1.setHttpOnly(false);
            cookie1.setSecure(false);
            //cookie1.setDomain("yft.nat100.top");
            httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.addCookie(cookie1);
            return true;
        }else {
            System.out.println("getToken为空");
        }

        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new RuntimeException("无token，请重新登录");
                }
                // 获取 token 中的 user id
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    throw new RuntimeException("401");
                }
                long id = Long.parseLong(userId);
                User user = userService.getUserByID(id);
                if (user == null) {
                    throw new RuntimeException("用户不存在，请重新登录");
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPhone())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new RuntimeException("401");
                }
                return true;
            }
        }
        returnJson(httpServletResponse);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    @ResponseBody
    private void returnJson(HttpServletResponse response){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        /*Cookie cookie = new Cookie("cookie", "value");
        cookie.setDomain("192.168.31.41");
        response.addCookie(cookie);*/
        try {
            writer = response.getWriter();
            Map<String, Object> result = PackageReturnResult.returnJson(400, "用户令牌token无效");
            result.put("code", ResponseCode.NEED_LOGIN.getCode());
            result.put("message","登录过时，需要重新登录");
            writer.print(result);
        } catch (IOException e){
            System.out.println("拦截器输出流异常");
            //LoggerUtil.logError(ECInterceptor.class, "拦截器输出流异常"+e);
        } finally {
            if(writer != null){
                writer.close();
            }
        }
    }
}